<?php

namespace App\Http\Controllers\LibApi;

use App\Models\LibBook;
use App\Models\LibBookBarcode;
use App\Models\LibBookRecom;
use App\Models\LibBorrowLog;
use App\Models\OnlineRegistration;
use App\Models\ShopBook;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 * 图书馆api接口  本地测试
 */
class LibApiController
{

    /**
     * 登录接口   （已对接） 读者证号登录
     * @param $account  读者证号
     * @param $password   密码
     */
    public function login($account, $password)
    {
        //默认密码为 123456
        if ($password != '123456') {
            return ['code' => 202, 'msg' => '登录失败,密码不正确'];
        }
        $onlineRegistrationModel = new OnlineRegistration();
        $res = $onlineRegistrationModel->where(function ($query) use ($account) {
            $query->where('reader_id', $account)->orWhere('id_card', $account);
        })->where('status', '<>', 4)
            ->first();
        if ($res) {
            $res = $res->toArray();
            $res['account'] = $res['reader_id'];
            $res['sex'] = $res['sex'] == 1 ? '男' : '女';
            $res['type'] = $res['card_type'];
            $res['start_time'] = $res['create_time'];
            $res['end_time'] = date('Y-m-d H:i:s', strtotime('+1 year'));
            $res['pavilion'] = null;
            $res['pavilion_note'] = config('other.lib_name');
            $res['status'] = '有效'; //必须是有效
            $res['cash'] = null;
            $res['diff_money'] = null;

            return ['code' => 200, 'msg' => '登录成功', 'content' => $res];
        }
        return ['code' => 202, 'msg' => '账号不存在'];
    }

    /**
     * 你借书我买单-添加右屏流通书目和采访信息和中央馆藏并借书-需授权
     *
     *  格式             CNMARC
       文献类型          图书
       书目库           CN中央书目库
       馆藏类型          图书
       馆藏所属馆        重庆市渝北区图书馆
       馆藏所属地        重庆市渝北区图书馆
       当前所在馆        新华书店阅读点  YB_XHSD
       当前所在地        新华书店阅读点  YB_XHSD
       经费来源          馆经费
       流通类型          一卡通中文图书
       装帧标识          平装/精装/线装
       载体标识          印刷型文献
     */
    public function addCirMarcAndAcqWorkAndAssetAndBorrowBook($data, $barcode, $account)
    {
        $libBookBarcodeModel = new LibBookBarcode();
        $is_exists_barcode = $libBookBarcodeModel->where('barcode', $barcode)->first();
        if ($is_exists_barcode) {
            return ['code' => 202, 'msg' => '此条形码已存在，请重新输入'];
        }

        $libBorrowLogModel = new LibBorrowLog();
        $field = ['book_name', 'author', 'price', 'press', 'pre_time', 'isbn', 'img', 'book_num'];
        $book_info = ShopBook::select($field)->where('isbn', $data['isbn'])->first();
        $book_info = $book_info->toArray();
        $book_info['barcode'] = $barcode;
        $book_info['callno'] = $book_info['book_num'];
        $book_info['classno'] = $book_info['book_num'];
        $res = $libBorrowLogModel->borrowBook($book_info, $account);

        //写入书目数据库
        $libBookModel = new LibBook();
        $lib_book_info = $libBookModel->where('isbn', $data['isbn'])->first();
        if (empty($lib_book_info)) {
            //加入书目数据
            $max_metaid = $libBookModel->max('metaid');
            $libBookModel->add([
                'metaid' => $max_metaid + 1,
                'metatable' => 'i_biblios',
                'book_name' => $data['book_name'],
                'author' => $data['author'],
                'press' => $data['press'],
                'pre_time' => $data['pre_time'],
                'isbn' => $data['isbn'],
                'old_isbn' => $data['isbn'],
                'price' => $data['price'],
                'img' => !empty($data['img']) ? $data['img'] : '',
                'intro' => !empty($data['intro']) ? $data['intro'] : '',
                'book_num' => $book_info['book_num'],
                'type_id' => null,
                'holding_num' => 1,
            ]);
            $book_id = $libBookModel->id;
        } else {
            $lib_book_info->holding_num = $lib_book_info->holding_num + 1;
            $lib_book_info->save();

            $book_id = $lib_book_info->id;
        }
        //添加馆藏
        $libBookBarcodeModel->add([
            'book_id' => $book_id,
            'barcode' => $barcode,
            'book_num' => $book_info['book_num'],
            'init_sub_lib' => '中心馆',
            'init_local' => '中心馆',
            'cur_sub_lib' => '中心馆',
            'cur_local' => '中心馆',
            'init_sub_lib_note' => '中心馆',
            'init_local_note' => '中心馆',
            'cur_sub_lib_note' => '中心馆',
            'cur_local_note' => '中心馆',
            'reg_date' => date('Y-m-d H:i:s'),
            'ecard_flag' => 1,
            'status' => 'h',
        ]);


        if ($res) {
            return ['code' => 200, 'msg' => '借阅成功', 'content' => ['returnDate' => date('Y-m-d H:i:s', strtotime("+1 month"))]]; //默认借阅成功
        }
        return ['code' => 202, 'msg' => '借阅失败'];
    }


    /**
     * 查询读者(基本信息+借阅信息+财经信息)-根据读者证号-需授权   （已对接）
     * @param $cardno  读者证号
     */
    public function getReaderInfo($account)
    {
        $onlineRegistrationModel = new OnlineRegistration();
        $res = $onlineRegistrationModel->where('reader_id', $account)->first();
        if ($res) {
            $res = $res->toArray();
            $res['account'] = $res['reader_id'];
            $res['readerFinInfo']['depositYuan'] = '0';
            $res['readerFinInfo']['arrearsYuan'] = '0';
            $res['readerBorrowInfo']['ableBorrowNum'] = '10';
            return ['code' => 200, 'msg' => '登录成功', 'content' => $res];
        }
        return ['code' => 202, 'msg' => '账号不存在'];
    }



    /**
     * 馆藏-查询馆藏分页列表-根据barcode馆藏条码号-需授权
     * @param $barcode 条形码
     *
     * //ecardflag 为1 则为一卡通。其它情况为非一卡通。
     */
    public function getAssetByBarcode($barcode)
    {
        $barcode_info = LibBookBarcode::where('barcode', $barcode)->first();
        if (empty($barcode_info)) {
            return ['code' => 202, 'msg' => '暂无数据'];
        }
        $book_info = LibBook::where('id', $barcode_info['book_id'])->first();
        if ($book_info) {
            $data['metaid'] = $book_info['metaid'];
            $data['metatable'] = 1;
            $data['book_name'] = $book_info['book_name'];
            $data['author'] = $book_info['author'];
            $data['book_num'] = $barcode_info['book_num'];  //返回了 classno （分类号） 和 callno（索书号）
            $data['classno'] = $barcode_info['book_num'];  //返回了 classno （分类号） 和 callno（索书号）
            $data['price'] = $book_info['price'];
            $data['img'] = $book_info['img'];
            $data['barcode'] = $barcode_info['barcode'];
            $data['page'] = 1;
            $data['intro'] = $book_info['intro'];

            $data['isbn'] = $book_info['isbn'];
            $data['status'] = $barcode_info['status'] == 'b' ? '入藏' : ($barcode_info['status'] == 'h' ? '借出' : '其他');
            $data['press'] = $book_info['press'];
            $data['pre_time'] = $book_info['pre_time'];
            $data['holding_address'] = '中心馆';
            $data['ecardFlag'] = 1;
            $data['curLocal'] = $barcode_info['curLocal'];
            // $data[$key]['holding_num'] = $val['assetCount'];//馆藏数量
            // $data[$key]['sublibAssetList'] = $val['sublibAssetList'];//分馆馆藏列表

            return ['code' => 200, 'msg' => '获取成功', 'content' => $data];
        }
        return ['code' => 202, 'msg' => '暂无数据'];
    }


    /**
     * 当前借阅记录   （已对接）
     * @param account 读者证号
     * @param page 页数
     * @param limit 读者证号
     * @param $ban_code 条形码
     * @return array
     */
    public function getNowBorrowList($account, $pageNum = 1, $pageSize = 10)
    {
        $libBorrowLogModel = new LibBorrowLog();
        $data = $libBorrowLogModel->lists($account, 2, null, null, $pageSize);

        if ($data['data']) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $data['data']];
        }
        return ['code' => 202, 'msg' => '暂无数据'];
    }

    /**
     * 查询读者历史借阅分页列表-根据读者证号 （已对接）
     * @param account 读者证号
     * @param pageNum 分页页码
     * @param pageSize 分页大小
     * @param year 借阅年份，不传默认为今年
     * @param startDate 借阅开始日期
     * @param endDate 借阅结束日期
     *
     * @param $all 是否返回所有数据   true  是  false  不是
     *
     * @return array
     */
    /** 读者借出Ea  */
    //BORROW("Ea", "读者借出"),
    /** 读者还回文献Eg */
    //  RETURN("Eg", "读者还回文献"),    //下面的枚举值，不能管什么情况，都会产生一条这个数据
    /** 读者续借Eb */
    // RENEW("Eb", "读者续借"),
    /** 读者过期Ec */
    //  OVERDUE("Ec", "读者过期"),
    /** 文献损坏Ed */
    //  DAMAGE("Ed", "文献损坏"),
    /** 读者丢失文献Ef */
    //  LOST("Ef", "读者丢失文献"),

    //文华状态
    /**
     * @return  RETURN("Eg", "读者还回文献"),
     * OVERDUE("Ec", "读者过期"),
     * DAMAGE("Ed", "文献损坏"),
     * 书已经还回
     *
     * LOST("Ef", "读者丢失文献"),
     *  书丢失，未还回。
     * 在我们系统    书丢失  也是指归还成功
     */
    public function getReturnData($account, $pageNum = 1, $pageSize = 100, $year =  null, $startDate = null, $endDate = null, $barcode = null, $all = false)
    {

        $libBorrowLogModel = new LibBorrowLog();
        $data = $libBorrowLogModel->lists($account, 1, $startDate, $endDate, $pageSize);

        if ($data) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $data['data']];
        }
        return ['code' => 202, 'msg' => '暂无数据'];
    }

    /**
     * 书目-opac书目检索-检索结果分页列表   (已对接)
     * @param $content 检索条件  一维数组
     * @param $sortName 排序字段   id   score
     * @param $sortOrder 排序方式
     * @param $page 页数
     * @param $limit 限制条数
     * @param $selectList 请求数据  ['isbn']
     *                              all 任意词
     *                              title 书名
                                   author 作者
                                   classno 分类号
                                   isbn isbn号
                                   callno 索书号
     *                              pubdate  出版年
     *                              publisher  出版社
     *                              subject  主题
     *                              ctrlno   控制号
     * @param $occurList 方式   ['and']    用大写的  AND 或 OR
     * @param $localList //查询(所属)馆藏地点 （馆藏书只能借阅这部分的书籍）
     *                默认图书馆馆藏地点代码： 查询馆藏地点  （书目，所属馆藏地点）
     *                查询的书目，只要有一本在这个馆藏，都可以查询出来
     *
     * @param $curLocalList //查询(所在)馆藏地点
     *
     */
    public function getBookInfo($content, $sortName = "id", $sortOrder = "desc", $page = 1, $limit = 10, $selectList = ["isbn"], $occurList =  ["AND"], $localList = null, $curLocalList = null, $type_id = null)
    {
        $keywords_type = $selectList[0];
        $res = LibBook::where(function ($query) use ($content, $keywords_type) {
            if (!empty($content)) {
                if ($keywords_type == 'all') {
                    $query->where('book_name', 'like', "%$content%")
                        ->orWhere('author', 'like', "%$content%")
                        ->orWhere('isbn', 'like', "%$content%")
                        ->orWhere('book_num', 'like', "%$content%");
                } else {
                    switch ($keywords_type) {
                        case 'title':
                            $query->where('book_name', 'like', "%$content%");
                            break;
                        case 'author':
                            $query->where('author', 'like', "%$content%");
                            break;
                        case 'isbn':
                            $query->where('isbn', 'like', "%$content%");
                            break;
                        case 'callno':
                            $query->where('book_num', 'like', "%$content%");
                            break;
                    }
                }
            }
        })->where(function ($query) use ($type_id) {
            if ($type_id) {
                $query->where('type_id', $type_id);
            }
        })->orderByDesc('id')
            ->paginate($limit)
            ->toArray();
        if ($res['data']) {
            $data = [];
            foreach ($res['data'] as $key => $val) {
                $data['data'][$key]['id'] = $val['id'];
                $data['data'][$key]['metaid'] = $val['metaid'];
                $data['data'][$key]['metatable'] = 1;
                $data['data'][$key]['book_name'] = $val['book_name'];
                $data['data'][$key]['access_number'] = $val['access_number'];
                $data['data'][$key]['author'] = isset($val['author']) ? $val['author'] : null;
                $data['data'][$key]['callno'] = isset($val['callno']) ? $val['callno'] : null; //索书号
                $data['data'][$key]['price'] = isset($val['price']) ? $val['price'] : null;

                $data['data'][$key]['isbn'] = isset($val['isbn']) ? $val['isbn'] : null;

                $data['data'][$key]['img'] = isset($val['img']) ? $val['img'] : 'default/default_lib_book.png';

                $data['data'][$key]['press'] = trim(explode(',', $val['press'])[0]);
                $data['data'][$key]['pre_time'] = $val['pre_time'];
                $data['data'][$key]['holding_num'] = 1; //馆藏数量
                $data['data'][$key]['sublibAssetList'] = 1; //分馆馆藏列表
            }

            $data['total'] = $res['total'];
            $data['per_page'] = $res['per_page'];
            $data['current_page'] = $res['current_page'];
            $data['last_page'] = $res['last_page'];
            return ['code' => 200, 'msg' => '获取成功', 'content' => $data];
        }
        return ['code' => 202, 'msg' => '暂无数据'];
    }

    /**
     * //客户端调用该协议根据metatable，metaid统计馆藏数量  之前的接口“/indiglibApi/api/v1/front/opacSearch/search”里的参数，assetCount，不能排除馆藏查询，所以使用此接口
     *access_token	是	String	令牌码
     *   metatable	是	String	书目库
     *   metaid	是	String	书目记录号
        initSublibList			包含所属馆	"initSublibList": ["CQL_DFWX","002"],
        notInInitSublibList			不在该所属馆	"notInInitSublibList": ["CQL_DFWX","002"],
        curSublibList			包含当前馆	"curSublibList": ["CQL_DFWX","002"],
        notInCurSublibList			不在该当前馆	"notInCurSublibList": ["CQL_DFWX","002"],
        initLocalList			包含所属馆藏地点	"initLocalList": ["CQL_DFWX","002"],
        notInInitLocalList			不在该所属馆藏地点	"notInInitLocalList": ["CQL_DFWX","002"],
        curLocalList			包含当前馆藏地点	"curLocalList": ["CQL_DFWX","002"],
        notInCurLocalList			不在该当前馆藏地点	"notInCurLocalList": ["CQL_DFWX","002"],
        inCirTypeList			包含流通类型	"inCirTypeList": ["CQL_DFWX","002"],
        notInCirTypeList			不在该流通类型	"notInInitLocalList": ["CQL_DFWX","002"],
     */
    public function countAssetNum($metatable, $metaid, $initSublibList = [], $notInInitSublibList = [], $curSublibList = [], $notInCurSublibList = [], $initLocalList = [], $notInInitLocalList = [], $curLocalList = [], $notInCurLocalList = [], $inCirTypeList = [], $notInCirTypeList = [])
    {

        $results['count'] = 1;
        return ['code' => 200, 'msg' => '获取成功', 'content' => $results];
    }
    /**
     * 书目-查询marc书目详细信息-根据metatable，metaid-需授权
     * @param  $metatable 书目库
     * @param  $metaid 书目记录号
     */
    public function getBookDetail($metatable, $metaid)
    {
        $book_info = LibBook::where('metaid', $metaid)->first();
        if ($book_info) {
            $data['id'] = $book_info['id'];;
            $data['metaid'] = $metaid;
            $data['metatable'] = $book_info['metatable'];
            $data['book_name'] = $book_info['book_name'];
            $data['author'] = $book_info['author'];
            $data['book_num'] = $book_info['book_num'];  //返回了 classno （分类号） 和 callno（索书号）
            $data['classno'] = $book_info['book_num'];  //返回了 classno （分类号） 和 callno（索书号）
            $data['price'] = $book_info['price'];
            $data['img'] = $book_info['img'];
            $data['page'] = 1;
            $data['intro'] = $book_info['intro'];
            $data['type_id'] = $book_info['type_id'];

            $data['access_number'] = isset($book_info['access_number']) ? $book_info['access_number'] : null;

            $data['isbn'] = $book_info['isbn'];
            $data['press'] = $book_info['press'];
            $data['pre_time'] = $book_info['pre_time'];
            // $data[$key]['holding_num'] = $val['assetCount'];//馆藏数量
            // $data[$key]['sublibAssetList'] = $val['sublibAssetList'];//分馆馆藏列表

            return ['code' => 200, 'msg' => '获取成功', 'content' => $data];
        }
        return ['code' => 202, 'msg' => '暂无数据'];
    }


    /**
     * 馆藏-查询馆藏分页列表-前台opac使用-需授权
     * @param  $metatable 书目库
     * @param  $metaid 书目记录号
     *
     * 返回  的status  状态     */
    /** 分编a ，不在opac上显示 */
    //CAT("a", "分编"),
    /** 入藏b*/
    //ONSHELF("b", "入藏"),
    /** 在装订c */
    //BINDING("c", "在装订"),
    /** 已合并d */
    //MERGED("d", "已合并"),
    /** 修补e */
    //REPAIRING("e", "修补"),
    /** 丢失f ，不在opac上显示 */
    //LOST("e", "丢失"),
    /** 剔除g ，不在opac上显示 */
    //DISCARD("g", "剔除"),
    /** 普通借出h */
    //LOAN("h", "普通借出"),
    /** 预约i */
    //RENT_LOAN("i", "预约"),
    /** 阅览借出j */
    //READING_LOAN("j", "阅览借出"),
    /** 资产状态:租出 k */
    //LEASE("k", "资产状态"),
    /** 预借l */
    //RESERVE("l", "预借"),
    /** 互借m */
    //INTER_LOAN("m", "互借"),
    /** 闭架借阅n */
    //CLOSE_LOAN("n", "闭架借阅"),
    /** 赠送o ，不在opac上显示 */
    //GIFT("o", "赠送"),
    /** 交换出p ，不在opac上显示 */
    //EXCHANGE("p", "交换出"),
    /** 调拨q ，不在opac上显示 */
    //DISPATCH("q", "调拨"),
    /** 转送t ，不在opac上显示 */
    //TRANSMIT("t", "转送"),
    /** 临时借出x ，不在opac上显示 */
    //TEMP_LOAN("x", " 临时借出"),
    /** 下架  */
    //SHELVES("s", "下架"),

    //ecardflag 为1 则为一卡通。其它情况为非一卡通。

    //$curLocalList 馆藏点  只允许查询的馆藏点

    public function getAssetPageInfoForOpac($metatable, $metaid, $curLocalList = null, $page = 1, $limit = 100)
    {
        $book_id = LibBook::where('metaid', $metaid)->value('id');
        $res = LibBookBarcode::where('book_id', $book_id)->get();
        if ($res) {
            $res = $res->toArray();
            $data = [];
            $i = 0;
            foreach ($res as $key => $val) {
                $data[$i]['metaid'] = $metaid;
                $data[$i]['metatable'] = 1;
                $data[$i]['status'] = $val['status'];
                $data[$i]['barcode'] = $val['barcode'];
                $data[$i]['book_num'] = $val['book_num'];;
                $data[$i]['initSublib'] = '中心馆'; //馆藏所属馆
                $data[$i]['initLocal'] = '中心馆'; //馆藏所属地
                $data[$i]['curSublib'] = '中心馆'; //当前所在馆
                $data[$i]['curLocal'] = '中心馆'; //当前所在地
                $data[$i]['initSublibNote'] = '中心馆'; //馆藏所属馆
                $data[$i]['initLocalNote'] = '中心馆'; //馆藏所属地
                $data[$i]['curSublibNote'] = '中心馆'; //当前所在馆
                $data[$i]['curLocalNote'] = '中心馆'; //当前所在地
                $data[$i]['regDate'] = null; //入藏时间
                $data[$i]['ecardFlag'] = isset($val['ecardFlag']) ? $val['ecardFlag'] : null; //ecardflag 为1 则为一卡通。其它情况为非一卡通。没返回就是 非一卡通
                $data[$i]['loanDate'] = isset($val['loanDate']) ? $val['loanDate'] : null; //借出时间 日期
                $data[$i]['loanTime'] = isset($val['loanTime']) ? $val['loanTime'] : null; //借出时间 时分秒
                $data[$i]['returnDate'] = isset($val['returnDate']) ? $val['returnDate'] : null; //应归还时间 日期
                $data[$i]['returnTime'] = isset($val['returnTime']) ? $val['returnTime'] : null; //应归还时间 时分秒
                $i++;
            }
        }
        if (!empty($data)) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $data];
        }
        return ['code' => 202, 'msg' => '暂无数据'];
    }


    /**
     * 校验读者借书权限接口
     * @param $account  读者证号
     * @param $barcode  馆藏条码号    新书  测试环境固定：01079300000147  渝中解放碑重庆书城
     * @param $barcode  馆藏条码号    新书  测试环境固定：01079300000153  渝中大坪重庆购书中心
     * @param $barcode  馆藏条码号    新书  正式环境固定：01039299999999  渝中解放碑重庆书城
     * @param $barcode  馆藏条码号    新书  正式环境固定：01039199999999  渝中大坪重庆购书中心
     * @return array
     * @param 01079300000147   01079300000153
     *
     *  private static $cqscAdminName = 'cqsc_bxdd_yz';//正式地址  操作管理员账号 渝中解放碑重庆书城
       private static $cqscPassword = '1234qwer';//正式地址  操作管理员密码

       private static $gszxAdminName = 'gszx_bxdd_yz';//正式地址  操作管理员账号 渝中大坪重庆购书中心
       private static $gszxPassword = '1234qwer';//正式地址  操作管理员密码
     */
    public function validateBorrow($account, $barcode = null, $shop_id = null)
    {
        return ['code' => 200, 'msg' => '可以借阅'];
    }

    /**
     * 流通-校验归还接口-需授权
     * @param $barcode  馆藏条码号
     * @return array
     */
    public function validateReturn($barcode)
    {

        return ['code' => 200, 'msg' => '可以归还'];
    }


    /**
     *  2.13流通-借书接口-需授权
     * @param $cardno  读者证号
     * @param $barcode  馆藏条码号
     * @param $borrowDateTime  借书时间
     * @return array
     */
    public function bookBorrow($cardno, $barcode, $borrowDateTime = null, $shop_id = null)
    {

        $libBorrowLogModel = new LibBorrowLog();
        $barcode_info = LibBookBarcode::where('barcode', $barcode)->first();
        $book_info = LibBook::where('id', $barcode_info['book_id'])->first();
        if (empty($book_info)) {
            return ['code' => 202, 'msg' => '借阅失败'];
        }
        $book_info = $book_info->toArray();
        $book_info['barcode'] = $barcode;
        $book_info['callno'] = $book_info['book_num'];
        $book_info['classno'] = $book_info['book_num'];
        $res = $libBorrowLogModel->borrowBook($book_info, $cardno);

        $barcode_info->status = 'h'; //借出
        $barcode_info->save(); //设置为借出状态

        if ($res) {
            return ['code' => 200, 'msg' => '借阅成功', 'content' => ['returnDate' => date('Y-m-d H:i:s', strtotime("+1 month"))]];
        }
        return ['code' => 202, 'msg' => '借阅失败'];
    }



    /**
     *  流通-归还接口-需授权
     * @param $barcode  馆藏条码号
     * @param $borrowDateTime  归还时间
     * @return array
     */
    public function bookReturn($barcode, $returnDate = null)
    {
        $libBorrowLogModel = new LibBorrowLog();
        $libBorrowLogModel->returnBook($barcode, $returnDate);

        //修改书目状态
        $barcode_info = LibBookBarcode::where('barcode', $barcode)->first();
        if (empty($barcode_info)) {
            return ['code' => 200, 'msg' => '归还成功'];
        }
        if ($barcode_info->status == 'b') {
            // return ['code' => 202, 'msg' => '此书已在馆'];
            return ['code' => 200, 'msg' => '操作成功'];
        }
        $barcode_info->status = 'b'; //入藏状态
        $res = $barcode_info->save(); //设置为借出状态

        if ($res) {
            return ['code' => 200, 'msg' => '归还成功'];
        }
        return ['code' => 202, 'msg' => '归还失败'];
    }

    /**
     *  流通-续借-续借单条-需授权
     * @param $barcode  馆藏条码号
     * @return array
     */
    public function renewBook($barcode)
    {
        $result['renew'] = 1;
        $result['returnDate'] = date('Y-m-d H:i:s', strtotime('+1 month'));
        $result['renewNum'] = 1;
        $libBorrowLogModel = new LibBorrowLog();
        $barcode_info = $libBorrowLogModel->where('barcode', $barcode)->orderByDesc('id')->first();
        if ($barcode_info) {
            if ($barcode_info['renew_num'] >= 1) {
                return ['code' => 203, 'msg' => '续借已达上限', 'content' => $result];
            }
            $barcode_info->renew_num = $barcode_info['renew_num'] + 1;
            $barcode_info->expire_time = $result['returnDate'];
            $barcode_info->save();
        }

        return ['code' => 200, 'msg' => '续借成功', 'content' => $result];
    }


    /**
     * 读者证-办证接口-需授权
     * @param $cardno  读者证号
     * @param $equipno  芯片号
     * @param $loginName  登录名
     * @param $idno       身份证
     * @param $realName  读者姓名
     * @param $password  登录密码
     * @param $cardType  读者证类型    45
     * @param $cerType  证件类别，身份证：idno    其他  字符串“6”
     * @param $eCardType
     * @param $etcCode  证件号码
     * @param $birth  出生年月日，格式：2019-01-01
     * @param $gender  性别，男：M 女：F
     * @param $workunit  工作单位
     * @param $address  联系地址
     * @param $zip  邮编
     * @param $phone  电话号码
     * @param $mobile  手机号码
     * @param $faxno  传真号码
     * @param $email  电子邮箱
     * @param $class1  分类1-所学专业
     * @param $class2  分类2-文化程度
     * @param $class3  分类3-行政职务
     * @param $class4  分类4-专业职称
     * @param $reviewLevel  书评级别
     * @param $acquisLevel  荐购级别
     * @param $notes  备注
     * @param $payWay  支付方式，现金：Cash  微信：WXin
     * @param $totalMoney  押金数额，单位：分
     *
     *
     *
     * 1：cerType 代码  6
     * 2：“前面 idno 身份证号码一致   为身份证号码 加 一个字母” 可以传
     * 3：idno 就不要传了
     * 4：其他的参数和之前参数一样     证件号码为  etcCode + 字母 Z
     * @return array
     * array(2) {
       ["params"] => array(29) {
           ["eCard"] => string(4) "true"
           ["cardno"] => string(14) "01131000000002"
           ["equipno"] => string(14) "01131000000002"
           ["loginName"] => string(14) "01131000000002"
           ["idno"] => string(14) "01131000000002"
           ["realName"] => string(12) "测试读者"
           ["password"] => string(7) "bxdd123"
           ["cardType"] => string(2) "45"
           ["eCardType"] => string(1) "1"
           ["cerType"] => string(4) "idno"
           ["etcCode"] => string(1) "1"
           ["birth"] => string(10) "2019-01-01"
           ["gender"] => string(1) "M"
           ["workunit"] => string(1) "1"
           ["address"] => string(1) "1"
           ["zip"] => string(1) "1"
           ["phone"] => string(11) "13258545262"
           ["mobile"] => string(11) "13258545262"
           ["faxno"] => string(1) "1"
           ["email"] => string(1) "1"
           ["class1"] => string(1) "1"
           ["class2"] => string(1) "3"
           ["class3"] => string(1) "3"
           ["class4"] => string(1) "3"
           ["reviewLevel"] => string(1) "1"
           ["acquisLevel"] => string(1) "1"
           ["notes"] => string(0) ""
           ["payWay"] => string(4) "Cash"
           ["totalMoney"] => string(5) "10000"
           }
           ["admin"] => array(4) {
           ["adminName"] => string(4) "bxdd"
           ["password"] => string(32) "ee4dd839109f5112def48acbbaf00113"
           ["loginWay"] => string(8) "DLibsApi"
           ["ip"] => string(9) "127.0.0.1"
           }
       }
     */
    public function readerIdAdd($data = null, $payWay = 'WXin')
    {
        return ['code' => 200, 'msg' => '办证成功'];
    }

    /**
     *  读者证-在线办证-获取在线办证参数集合
     */
    public function getOnlineReaderCardCreateParam()
    {

        return ['code' => 200, 'msg' => '获取成功', 'content' => null];
    }

    /**
     *  读者-查询读者列表(非注销)-根据身份证号码-需授权  (已对接)
     * @param $idno  身份证号码
     * @return array
     *
     *  //查询的是  ，是否在本馆办过读者证，在其他馆办理过的，查询不到
     */
    public function getReaderPageInfoByIdno($idno, $page = 1, $limit = 10)
    {
        $onlineRegistrationModel = new OnlineRegistration();
        $res = $onlineRegistrationModel->where('id_card', $idno)->first();

        if ($res) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $res];
        }
        return ['code' => 202, 'msg' => '此身份证号码不存在'];
    }

    /**
     *  读者证-挂失-需授权
     * @param $account  读者证号
     * @return array
     */
    public function lost($account)
    {

        return ['code' => 200, 'msg' => '挂失成功'];
    }

    /**
     *  读者证-挂失恢复-需授权
     * @param $account  读者证号
     * @return array
     */
    public function lostRecover($account)
    {
        return ['code' => 200, 'msg' => '取消挂失成功'];
    }


    /**
     * 读者证-更新读者密码-需授权
     * @param $account  读者证号
     * @param $origPassword  读者旧密码
     * @param $newPassword  读者新密码
     * @return array
     */
    public function updateReaderPassword($account, $origPassword, $newPassword)
    {

        return ['code' => 200, 'msg' => '修改成功'];
    }
    /**
     * 读者财经-欠款-查询读者欠款分页列表-根据读者证号-需授权
     * @param account 读者证号
     */
    public function getReaderArrearsListPageInfo($account, $page = 1, $limit = 10)
    {
        $res["list"] = [
            [
                "finAccountId" => 310827,
                "money" => 9900,
                "moneyYuan" => "99.00",
                "costType" => "Depi",
                "costTypeNote" => "专项手动欠款",
                "updateDate" => "2021-01-04",
                "updateTime" => "15:21:28",
                "adminName" => "wh",
                "notes" => "首次芯片损坏",
                "finEventId" => 382704
            ],
            [
                "finAccountId" => 111,
                "money" => 9900,
                "moneyYuan" => "99.00",
                "costType" => "Depi",
                "costTypeNote" => "图书超期滞纳金",
                "updateDate" => "2021-01-04",
                "updateTime" => "15:21:28",
                "adminName" => "wh",
                "notes" => "首次芯片损坏",
                "finEventId" => 382704
            ]
        ];

        return ['code' => 200, 'msg' => '获取成功', 'content' => $res];
    }

    /**
     * 读者财经-欠款-支付欠款-需授权
     * @param readerId 读者ID(为空或空字符串则查全部分馆) 为图书馆的id
     * @param arrearsIdList 欠费列表id
     * @param payWay 支付方式，现金：Cash，微信：WXin ，支付宝：APay
     */
    public function payArrears($account = null, $arrearsIdList = [], $payWay = '1')
    {
        return ['code' => 200, 'msg' => '缴费成功'];
    }


    /**
     * 2.23微信-获取微信accessToken
     * @param access_token 文华accesstoken
     */
    public function getWxAccessToken()
    {
        return ['code' => 200, 'msg' => '获取成功', 'content' => null];
    }

    /**
     * 云cloud-读者-校验读者身份证号是否存在(校验是否存在非注销状态读者)-需授权
     * 这个接口不能判断身份证是否在本馆办过证，还需要另外一个接口，配合查询是否在本馆办过证的接口（如果返回是，则在本馆办过证，如果返回否，表示在其他馆办过证）
     * @param idno 身份证号码
     */
    public function validateIdnoIsExist($idno)
    {
        $onlineRegistrationModel = new OnlineRegistration();
        $res = $onlineRegistrationModel->where('id_card', $idno)->first();

        //原接口判断
        if ($res) {
            return ['code' => 200, 'msg' => '此身份证号码已存在', 'content' => $res]; //表示办过证
        }
        return ['code' => 202, 'msg' => '身份证号码不存在']; //表示未办过证
    }

    /**
     * 读者证-证延期-网上服务读者自助延期-需授权
     * @param $account 读者证号
     */
    public function extendByReaderSelf($account)
    {
        $data['cardno'] = $account;
        $data['begDate'] = date('Y-m-d H:i:s');
        $data['endDate'] = date('Y-m-d H:i:s', strtotime('+1 year'));

        return ['code' => 200, 'msg' => '操作成功', 'content' => $data];
    }


    /**
     * front-微信-读者绑定-需授权（我们平台绑定后，推送绑定在文华系统）
     * @param $readerId 读者ID
     * @param $openid   微信open_id
     */
    public function wxBind($readerId, $open_id)
    {

        return ['code' => 200, 'msg' => '操作成功', 'content' => null];
    }

    /**
     * 2.7front-微信-解除读者绑定-需授权（我们平台解绑后，推送解绑在文华系统）
     * @param $readerId 读者ID
     * @param $openid   微信open_id
     */
    public function wxUnBind($readerId, $open_id)
    {

        return ['code' => 200, 'msg' => '操作成功', 'content' => null];
    }

    /**
     * 2.23读者-查询读者(基本信息)-根据微信openid-需授权
     * @param $openid   微信open_id
     */
    public function getReaderByOpenid($open_id)
    {

        return ['code' => 200, 'msg' => '操作成功', 'content' => null];
    }

    /**
     * //读者-查询读者(基本信息)-根据读者id-需授权
     * @param $reader_id   文华系统读者id   在 条形码获取信息接口会返回一个  readerId  表示当前借阅用户的id
     */
    public function getReaderById($reader_id)
    {
        return ['code' => 200, 'msg' => '操作成功', 'content' => null];
    }

    /**
     * 获取借阅，归还，管理员账号
     * @param 书店 id
     */
    public function getManageAccount($shop_id = null) {}


    /**
     * 2.12front-读者借阅排行榜-结果列表
     * @param $sublib  分馆代码(为空或空字符串则查全部分馆)
     * @param $docType   文献类型(为空或空字符串则查全部文献类型)
     * @param $timeLimit   时间范围(距离今天多少天，时间范围只能为最近一周(7天)，最近一个月(30天)，最近三个月(90天)和最近六个月(180天)（timeLimit不为空时，起始时间和结束时间可为空，同时不为空时起始时间和结束时间的优先级更高）
     * @param $startDate   开始日期
     * @param $endDate   结束日期
     */
    public function frontReader($sublib, $docType, $timeLimit, $startDate = null, $endDate = null)
    {
        // $adminName = self::$adminName;
        // $password = self::$password;

        $access_token = Cache::get('yzqlib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$frontReader;

        $param = [
            'sublib' => $sublib,
            'docType' => $docType,
            'timeLimit' => $timeLimit,
            'startDate' => $startDate,
            'endDate' => $endDate,
        ];

        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("yzqlib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入错误日志
        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '操作成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }

    /**
     * 2.13前台front-读者年龄借阅排行榜-结果列表
     * @param $sublib  分馆代码(为空或空字符串则查全部分馆)
     * @param $docType   文献类型(为空或空字符串则查全部文献类型)
     * @param $startDate   开始日期
     * @param $endDate   结束日期
     */
    public function frontReaderAge($sublib, $docType, $startDate, $endDate)
    {
        // $adminName = self::$adminName;
        // $password = self::$password;

        $access_token = Cache::get('yzqlib_access_token');
        if (empty($access_token)) {
            $access_token = $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$frontReaderAge;

        $param = [
            'sublib' => $sublib,
            'docType' => $docType,
            'startDate' => $startDate,
            'endDate' => $endDate,
        ];

        $param = json_encode($param);

        $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true);
        $results = json_decode($result, true); //json字符串转为数组
        dump($results);
        die;
        if (isset($results['error']) && $results['error'] == 'invalid_token') {
            $access_token = $this->getAccessToken();
            // cache("yzqlib_access_token", $access_token, 3600);//缓存3600秒,覆盖掉之前的token
            $result = $this->RequestCurl($url . '?access_token=' . $access_token, $param, true); //然后重新请求
            $results = json_decode($result, true); //json字符串转为数组
        }

        //写入错误日志
        Log::channel('libapi')->info('URL：' . $url);
        Log::channel('libapi')->info(json_decode($param, true));
        //写入错误日志
        Log::channel('libapi')->info($results);

        if (isset($results['code']) && $results['code'] == 1) {
            return ['code' => 200, 'msg' => '操作成功', 'content' => $results['objectData']];
        }
        return ['code' => 202, 'msg' => $results['message']];
    }


    /**
     * @param $url
     * @param null $params
     * @param bool $json  json  格式数据    Content-Type  需要修改  成 application/json
     * @return mixed
     */
    private  static  function RequestCurl($url, $params = null, $json = false)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        if (!empty($params)) {
            if (is_array($params)) {
                //如果传的是数组，就要进行对参数进行 &拼接
                $params = http_build_query($params);
            }
            if ($json) {
                curl_setopt(
                    $ch,
                    CURLOPT_HTTPHEADER,
                    array(
                        'Content-Type: application/json',
                        'Content-Length: ' . strlen($params)
                    )
                );
            }
            // curl_setopt($ch, CURLOPT_POST, 1);
            // curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }
        //都是用post格式
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

        $body = curl_exec($ch);
        // dump(curl_error($ch));
        curl_close($ch);
        return $body;
    }
}
